<script setup>
import { ref, computed, inject } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

import { useSetUpStore } from '@/stores'
const setUpStore = useSetUpStore()

// 折叠面板
const collapseName = ref([''])
// 主题单选框
const themeChecked = ref(1)
themeChecked.value = setUpStore.getThemeIndex()
// 显示选择时间弹窗
const showSelectDate = ref(false)
const selectDateTab = ref(0)

const lightCurrentTime = ref([]) // 浅色风格时间
lightCurrentTime.value = setUpStore.getLightTime()
const darkCurrentTime = ref([]) // 深色风格时间
darkCurrentTime.value = setUpStore.getDarkTime()
const lightCurrentTimeVO = computed(() => setUpStore.getLightTime())
const darkCurrentTimeVO = computed(() => setUpStore.getDarkTime())
const formatter = (type, option) => {
  if (type === 'hour') {
    option.text += '时'
  }
  if (type === 'minute') {
    option.text += '分'
  }
  return option
}
// 主题切换
const themeChange = (index) => {
  themeChecked.value = index
  setUpStore.setThemeIndex(index)
  showNotify({ type: 'success', duration: 1000, message: '主题切换成功' })
}

const setThemeTime = () => {
  if (
    lightCurrentTime.value.every(
      (element, index) => element === darkCurrentTime.value[index]
    )
  ) {
    showNotify({ type: 'warning', message: '请选择不同时间' })
    return
  }
  setUpStore.setLightTime(lightCurrentTime.value)
  setUpStore.setDarkTime(darkCurrentTime.value)
  themeChange(3)
  showSelectDate.value = false
  // nextTick(() => {
  //   selectDateTab.value = 0
  // })
}

const musicPlayer = inject('musicPlayerRef')
// 定时关闭相关
const timingCloseRef = ref(null) // 定时关闭折叠面板
const timingCloseSwitch = ref(false)

const closeTime = ref(30) // 关闭时间
const sliderTime = ref(30) // 滑动条时间

const showClosingMode = ref(false) // 显示关闭方式
const closingModeActions = [
  { name: '立即关闭', subname: '计时结束后立即关闭' },
  { name: '播完整首歌后关闭', subname: '计时结束后,播完整首歌再关闭' }
]
const closingMode = computed(() => setUpStore.getClosingMode()) // 关闭方式
let timer = null // 定时器
// 开关定时关闭
const onTimingClose = (value) => {
  clearTimeout(timer)
  timingCloseRef.value.toggle(value)
  // plus.runtime.quit()

  if (value) {
    // 开
    showNotify({
      type: 'success',
      message: `已开启定时关闭,${closeTime.value}分钟后关闭`
    })
    timer = setTimeout(
      () => {
        console.log(closingMode.value)
        if (closingMode.value === '立即关闭') {
          if (!musicPlayer.value.audioPlay.paused) {
            musicPlayer.value.playOrPaused()
          }
          timingCloseSwitch.value = false
          onTimingClose(false)
          plus.runtime.quit()
        } else {
          const musicCurrentTime = parseInt(
            musicPlayer.value.audioPlay.currentTime
          )
          const totalTime = parseInt(musicPlayer.value.audioPlay.duration)
          // closeTime.value = totalTime - musicCurrentTime
          timer = setTimeout(
            () => {
              if (!musicPlayer.value.audioPlay.paused) {
                musicPlayer.value.playOrPaused()
              }
              timingCloseSwitch.value = false
              onTimingClose(false)
              plus.runtime.quit()
            },
            (totalTime - musicCurrentTime) * 1000
          )
        }
        console.log('计时结束')
      },
      closeTime.value * 60 * 1000
      // 5000
    )
  } else {
    // 关
    // clearTimeout(timer)
    showNotify({
      type: 'success',
      message: `已关闭定时关闭`
    })
  }
}

// 时间滑动条值改变
const onTimeSliderChange = (value) => {
  if (value > 60) {
    showCustomTimeDialog.value = true
  } else {
    closeTime.value = value
    onTimingClose(true)
  }
}
// 自定义时间
// const onCustomTime = () => {
//   console.log(customTime.value)

//   if (
//     !customTime.value ||
//     customTime.value === '0' ||
//     customTime.value > 1440
//   ) {
//     showNotify({ type: 'warning', message: '请输入60分钟以内的数字' })
//     return
//   } else {
//     closeTime.value = customTime.value
//     // showCustomTimeDialog.value = false
//   }
// }
const onCustomTime = (action) => {
  if (action !== 'confirm') {
    sliderTime.value = closeTime.value
    return true
  }
  if (
    !customTime.value ||
    customTime.value === '0' ||
    customTime.value > 1440
  ) {
    showNotify({ type: 'warning', message: '自定义关闭时间应为1~1440分钟' })
    customTime.value = ''
    return false
  } else {
    closeTime.value = customTime.value
    onTimingClose(true)

    return true
  }
}

const showCustomTimeDialog = ref(false) // 自定义时间弹窗
const timeInputRef = ref(null) // 自定义时间输入框
const customTime = ref() // 自定义时间

// onMounted(() => {
//   const sliderButton = document.querySelector('.van-slider__button')
//   sliderButton.addEventListener('click', () => {
//     console.log('挂载')
//     onTimeSliderChange(sliderTime.value)
//   })
//   console.log(sliderButton.click)
// })
</script>
<template>
  <div class="set-up">
    <div class="set-up-header">
      <van-nav-bar
        fixed
        :placeholder="true"
        title="设置"
        left-arrow
        @click-left="router.go(-1)"
      />
    </div>
    <div class="set-up-content">
      <van-collapse v-model="collapseName">
        <van-collapse-item title="主题" name="1">
          <van-radio-group v-model="themeChecked">
            <van-cell-group>
              <van-cell title="浅色风格" clickable @click="themeChange(1)">
                <template #right-icon>
                  <van-radio :name="1" />
                </template>
              </van-cell>
              <van-cell title="深色风格" clickable @click="themeChange(2)">
                <template #right-icon>
                  <van-radio :name="2" />
                </template>
              </van-cell>
              <!-- :label="`浅色风格：${lightCurrentTime.join(':')} \n 深色风格：${darkCurrentTime.join(':')}`" -->
              <van-cell @click="themeChange(3)" clickable center>
                <template #title>
                  <div class="cell-title">
                    <span>根据时间自动切换&nbsp;</span>
                    <van-button
                      @click.stop="showSelectDate = true"
                      type="primary"
                      size="mini"
                      plain
                    >
                      设置时间
                    </van-button>
                  </div>
                </template>
                <template #label>
                  <p>{{ lightCurrentTimeVO.join(':') }} 后浅色风格</p>
                  <p>{{ darkCurrentTimeVO.join(':') }} 后深色风格</p>
                </template>
                <template #right-icon>
                  <van-radio :name="3" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
          <van-overlay
            :show="showSelectDate"
            @click.self="showSelectDate = false"
            z-index="999"
          >
            <van-picker-group
              v-model:active-tab="selectDateTab"
              class="picker-group"
              title="选择时间"
              :tabs="['浅色风格', '深色风格']"
              next-step-text="下一步"
              @confirm="setThemeTime()"
              @cancel="showSelectDate = false"
            >
              <van-time-picker
                v-model="lightCurrentTime"
                :formatter="formatter"
              />
              <van-time-picker
                v-model="darkCurrentTime"
                :formatter="formatter"
              />
            </van-picker-group>
          </van-overlay>
        </van-collapse-item>

        <!-- <van-collapse-item ref="timingClose" title="定时关闭" name="2" readonly>
          <template #default> 定时 关闭 </template>
          <template #right-icon>
            <van-switch
              @click.capture="onTimingClose()"
              v-model="timingCloseSwitch"
            />
          </template>
        </van-collapse-item> -->
        <van-collapse-item
          ref="timingCloseRef"
          title="定时关闭"
          name="2"
          readonly
        >
          <!-- @click="timingCloseSwitch = !timingCloseSwitch" -->
          <template #default>
            <!-- 关闭时间 -->
            <div class="time-slider-wrap">
              <div class="point">
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
              </div>
              <van-slider
                v-model="sliderTime"
                @change="onTimeSliderChange"
                :step="15"
                max="75"
                min="15"
                button-size="18px"
                active-color="var(--null)"
              />
              <div class="time-slider-text">
                <span>15分钟</span>
                <span>30分钟</span>
                <span>45分钟</span>
                <span>60分钟</span>
                <span>自定义</span>
              </div>
            </div>
            <!-- 自定义关闭时间 -->
            <van-dialog
              v-model:show="showCustomTimeDialog"
              title="自定义时间"
              show-cancel-button
              @opened="timeInputRef.focus()"
              :before-close="onCustomTime"
            >
              <!-- @confirm="onCustomTime()" -->
              <!-- :before-close="customTimeDialogBeforeClose" -->
              <van-cell-group inset :border="true">
                <van-field
                  ref="timeInputRef"
                  v-model="customTime"
                  type="digit"
                  :clearable="true"
                  clear-trigger="always"
                  maxlength="4"
                >
                  <template #extra> 分钟 </template>
                </van-field>
              </van-cell-group>
            </van-dialog>

            <!-- 关闭方式 -->
            <van-cell
              title="关闭方式"
              is-link
              :value="closingMode"
              style="padding: 0"
              @click.stop="showClosingMode = true"
            />
            <van-action-sheet
              v-model:show="showClosingMode"
              :actions="closingModeActions"
              close-on-click-action
              @select="(action) => setUpStore.setClosingMode(action.name)"
            />
          </template>
          <template #label>
            <van-count-down
              v-if="timingCloseSwitch"
              :time="closeTime * 60 * 1000"
              style="font-size: 12px"
            />
          </template>
          <template #right-icon>
            <van-switch @change="onTimingClose" v-model="timingCloseSwitch" />
          </template>
        </van-collapse-item>
      </van-collapse>
    </div>
  </div>
</template>
<style scoped>
/* 主题cell标题样式 */
.cell-title {
  display: flex;
  align-items: center; /* 垂直居中 */
  /* height: 100%; 确保容器高度占满其父元素 */
}
/* 时间选择器样式 */
.picker-group {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
}

/* 定时关闭 */
/* ::v-deep .van-slider__bar { */
/* --van-slider-active-background: var(--van-gray-3); */
/* --van-slider-active-background: var(--common-background-color); */
/* } */
.time-slider-wrap {
  position: relative;
  margin: 17px;
  /* height: 38px; */
  padding-bottom: 38px;
}
.time-slider-wrap .point {
  width: 104.5%;
  position: absolute;
  display: flex;
  justify-content: space-between;
}
.time-slider-wrap .point ::before {
  content: '';
  display: inline-block;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  /* background-color: var(--van-gray-8); */
  background-color: var(--van-slider-inactive-background);
  /* background-color: red; */
  transform: translate(-50%, -50%);
}
.time-slider-wrap .time-slider-text {
  width: 110%;
  position: absolute;
  display: flex;
  justify-content: space-between;
  transform: translate(-5%, 75%);
  font-size: 13px;
}

/* 时间输入框样式 */
::v-deep .van-field__body {
  background-color: var(--van-field__control-background-color);
  border: var(--van-field__control-border);
  height: 27px;
}
</style>
